package com.mujin.keji.collectionsystem.http;

import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.mujin.keji.collectionsystem.CcsApplication;
import com.mujin.keji.collectionsystem.Constant;
import com.mujin.keji.collectionsystem.interceptor.AddCookiesInterceptor;
import com.mujin.keji.collectionsystem.interceptor.ReceivedCookiesInterceptor;
import com.mujin.keji.collectionsystem.ssl.SafeHostnameVerifier;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 上传文件需要实时监听进度条用到的Retrofit
 */
public class UploadRetrofit {
    private static final String TAG = "UploadRetrofit";

    /**
     * 实例化Retrofit对象
     *
     * @param listener
     * @return
     */
    public static ApiService getInstance(UploadListener listener) {
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new UpLoadProgressInterceptor(listener))
                .connectTimeout(Constant.Server.TIME_OUT, TimeUnit.SECONDS)       //超时时间
                .readTimeout(Constant.Server.TIME_OUT,TimeUnit.SECONDS)
                .writeTimeout(Constant.Server.TIME_OUT,TimeUnit.SECONDS)
                .addNetworkInterceptor(new StethoInterceptor())
                .addInterceptor(new AddCookiesInterceptor()) //这部分
                .addInterceptor(new ReceivedCookiesInterceptor()) //这部分
                .hostnameVerifier(new SafeHostnameVerifier())
                .sslSocketFactory(CcsApplication.getSslSocket())  //
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.Server.ROOT_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return retrofit.create(ApiService.class);
    }

}
